#定义数库工具类
import pymysql


class DBTool:

    #创建连接
    @classmethod
    def __create_conn(cls):
        conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='123456',
                               db='mydb', charset="utf8")
        return conn
    #查询方法 查一条语句
    @classmethod
    def query(cls,sql):
        conn= None
        cursor = None
        resp=None
        #创建连接
        try:
            #创建连接
            conn=DBTool. __create_conn()
            # 创建游标
            cursor=conn.cursor()

            #执行sql语句
            cursor.execute(sql)
            #提取数据
            resp=cursor.fetchone()
            #提交事务
            conn.commit()
        except Exception as e:
            conn.rollback()
            print("查询失败",e)
        finally:
        # 关闭游标
            cursor.close()
            # 关闭连接
            conn.close()
            return resp
    #增删改
    @classmethod
    def db_uid(cls,sql):
        conn = None
        cursor = None
        try:
            # 创建连接
            conn =DBTool.__create_conn()
            # 创建游标
            cursor=conn.cursor()
            #执行sql语句
            cursor.execute(sql)
            print("影响了几条数据：",conn.affected_rows())
            #操作成功 提交事务
            conn.commit()
        except Exception as e:
            print("操作失败",e)
            conn.rollback()
        finally:

            # 关闭游标
            cursor.close()
            # 关闭连接
            conn.close()

if __name__ == '__main__':
    print(DBTool.query("select * from students"))
